using System;
using System.Collections.Generic;
//using ChatGPTWrapper;
using UnityEngine;
[System.Serializable]
public class ChatListVCData
{
    public List<Chat> chats;
    public long defaultChat;
}

public class ChatListViewController : ViewController
{  
    private MBattleController m_BattleContorller;
    public MBattleController mBattleController
    {
        get
        {
            if (m_BattleContorller == null)
                m_BattleContorller = GetComponentInParent<MBattleController>();
            return m_BattleContorller;
        }
    }
    private MBattleSceneController battleSceneController => GetComponentInParent<MBattleSceneController>();
    MBattleController battleScene => battleSceneController .mBattleController;

    ChatListPanel m_Panel;
    public ChatListPanel panel => m_Panel;


   // public ChatGPTConversation chatGPTConversation;
    
    public int maxRetryCount = 1;

    private int m_TryCount = 0;

    private bool editorTestAPIKey = true;

    private int maxChatADay = 20;
    int chatCount
    {
        get
        {
            return PlayerPrefs.GetInt("ChatCount");
        }
        set
        {
            PlayerPrefs.SetInt("ChatCount",value);
        }
    }
    int lastDay
    {
        get
        {
            return PlayerPrefs.GetInt("LastDay");
        }
        set
        {
            PlayerPrefs.SetInt("LastDay",value);
        }
    }
    
    [SerializeField]
    ChatListVCData m_Data;
    public ChatListPanel Init(ChatListVCData data)
    {
        if (m_Panel == null)
            m_Panel = InitUI();

        GameDebug.LogError($"data != null:{data != null}");

        m_Data = data;
        m_Panel.Init(data,OnClickSend);

        return m_Panel;
    }

    private void Start()
    {
//        if(chatGPTConversation == null)
//            chatGPTConversation = Instantiate(Resources.Load<ChatGPTConversation>("ChatGPTConversation"),transform);
        
//        chatGPTConversation.chatGPTResponse.AddListener(OnGPTResponse);
//        chatGPTConversation.onError = this.OnReqError;

//#if UNITY_EDITOR
//        if (!editorTestAPIKey)
//#endif
//        {
//            if (MGame.instance && !string.IsNullOrEmpty(MGame.instance.chatgptKey))
//            {
//                chatGPTConversation._apiKey = MGame.instance.chatgptKey;
//            }
//        }
        
        int curLoginDay = System.DateTime.Now.Day;
        if (lastDay != curLoginDay)
        {
            lastDay = curLoginDay;

            chatCount = 0;
        }
    }

    protected ChatListPanel InitUI()
    {
        var prefab = ResourceManager.Load<ChatListPanel>(ViewPath.chatListPanel);
        if (prefab == null)
        {
            GameDebug.LogError("HomePanel prefab null");
            return null;
        }
        m_Panel = GameObject.Instantiate<ChatListPanel>(prefab, transform);
        m_Panel.SetViewController(this);
        return m_Panel;
    }
    protected override void WillLoadView()
    {
        base.WillLoadView();
    }

    private string curContent;
    private void OnClickSend(string content)
    {
        AddChat(true, content);

        if (chatCount <= maxChatADay)
        {
            chatCount++;
            RequestChat(content);
        }
        else
        {
            AddChat(false,"Sorry, I've talked too much and I need a rest. See you tomorrow");
        }
    }

    string girlName
    {
        get
        {
            string girlname = "Marry";
            var candidate = ConstantData.instance.GetCandidate(m_Data.defaultChat);
            if (candidate != null)
            {
                girlname = candidate.name;
            }

            return girlname;
        }
    }
    void RequestChat(string content)
    {
        curContent = content;
        
        string question = $"'{content}', response as a girl named {girlName} in a new line start with '{girlName}:', less than 25 words";

#if UNITY_EDITOR
        Debug.Log(question);
#else
        GameDebug.Log(question);
#endif
        //chatGPTConversation.SendToChatGPT(question);
    }

    public void OnGPTResponse(string res)
    {
        GameDebug.Log($"ai response:{res}");
        string answerSplit = $"{girlName}:";
        string[] lines0 = res.Split(answerSplit.ToCharArray());
        //GameDebug.LogError($"lines0:{lines0.GetArrStr()}");

        if (lines0.Length > 0)
        {
            string right = lines0[1];
            AddChat(false, right);
        }
        else
        {
            AddChat(false, res);
        }
    }

    void AddChat(bool me, string content)
    {
        if(me)
            MGame.instance.MUser.AddDialogue(MGame.instance.MUser.id, m_Data.defaultChat,content, UnityFunctions.GetTimeStampSeconds());
        else
            MGame.instance.MUser.AddDialogue(m_Data.defaultChat, MGame.instance.MUser.id, content, UnityFunctions.GetTimeStampSeconds());

        m_Panel.Refresh(GetVCData(MGame.instance.MUser));
    }
    
    private void OnReqError(string obj)
    {
        DoActionDelay.DelayAction(2f, Retry);
        
        GameDebug.LogError($"error OnReqError:{obj}");
    }
    
    public Action<string> onEnd;
    public Action<string> onError;
    
    void Retry()
    {
        m_TryCount++;
        
        if (m_TryCount >= maxRetryCount)
        {
            // if(mBattleController)
                //mBattleController.OnReqError();
                
            onError?.Invoke("");
            GameDebug.LogError($"chat, on req error");
            
            AddChat(false,"Sorry, there is something error");
        }
        else
        {
            
            RequestChat(curContent);
        }
    }
    /*void OnParseError()
    {
        //GameDebug.LogError($"error parse question:{curQuestion}");
            
        if (m_TryCount > maxRetryCount)
        {
            //if(mBattleController)
            //    mBattleController.OnError();
        }
        else
        {
            Retry();
        }
    }*/
    
    public override void WillHideView()
    {
        base.WillHideView();

        if (m_Panel)
        {
            m_Panel.PlayHideAnim();
        }
    }


    public override void OnViewDelete()
    {
        base.OnViewDelete();

        if (m_Panel)
        {
            Destroy(m_Panel.gameObject);
        }
        m_Panel = null;
    }

    public static ChatListVCData GetVCData(MGameUser gameUser)
    {
        ChatListVCData data = new ChatListVCData();
        
        data.chats = new List<Chat>(gameUser.chats);
        if (data.chats.Count > 0)
        {
            data.defaultChat = data.chats[data.chats.Count - 1].userId1;
        }
        return data;
    }

}